package com.yunkaweilai.android.fragment.guadan;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.fragment.operation.TimeShopListFragment;
import com.yunkaweilai.android.interfaces.DialogPayInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.shop.ShopSkuInfoModel;
import com.yunkaweilai.android.model.shop.ShopTypeModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.zxing.Kutils;
import com.yunkaweilai.android.view.dialog.guadan.GuadanNextDialog;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 计次界面
 * Created by Administrator on 2017/6/13.
 */

public class GuadanTimeShopTypeFragment extends BaseFragment implements DialogPayInterface {
    @BindView(R.id.id_listView_left)
    ListView idListViewLeft;
    @BindView(R.id.id_tabLayout)
    TabLayout idTabLayout;
    @BindView(R.id.id_viewPager)
    ViewPager idViewPager;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    Unbinder unbinder;
    @BindView(R.id.id_tv_all_price)
    TextView idTvAllPrice;
    @BindView(R.id.id_tv_checkout)
    TextView idTvCheckout;
    @BindView(R.id.content_view)
    LinearLayout contentView;
    @BindView(R.id.id_tv_buy_num)
    TextView idTvBuyNum;
    private Map<String, ShopSkuInfoModel> selectedMaps = BaseApplication.getSelectedMaps();
    private ArrayList<ShopTypeModel> AllTypeList = new ArrayList<>();
    private CommonAdapter<ShopTypeModel> leftAdapter;
    private JSONObject listJson;//各种分类的列表
    private String gid;
    private String goodsStr = "";

    public static GuadanTimeShopTypeFragment newInstance(String gid) {
        GuadanTimeShopTypeFragment fragment = new GuadanTimeShopTypeFragment();
        fragment.gid = gid;
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_pt_shop_consumption;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.SHOP_CART_INFO_REFRESH) {
                if (event.flag) {
                    selectedMaps = BaseApplication.getSelectedMaps();
                    refreshShopCart();
                    leftAdapter.notifyDataSetChanged();

                }
            }
        }
    }

    private void refreshShopCart() {

        double price = 0;
        double nums = 0;
        for (String key : selectedMaps.keySet()) {
            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(key);
//            double buy_price = shopSkuInfoModel.getBuy_num() * shopSkuInfoModel.getShop_price();
            double buy_price = Kutils.cheng(shopSkuInfoModel.getBuy_num(), shopSkuInfoModel.getShop_price());

            price = Kutils.add(buy_price, price);
            nums = Kutils.add(nums, shopSkuInfoModel.getBuy_num());
        }
        String prices = Utils.ManageMoney(price+"");
        idTvAllPrice.setText(prices + "");
        idTvBuyNum.setText(nums+"");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initAdapter();
        initClick();
        initHttp();
        idTvCheckout.setText("确定");
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        refreshShopCart();
    }

    private void initHttp() {
        HttpRequest.postUrl(Api.TIME_TYPE_LIST)
                .log(TAG).execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(String json) {
                boolean checkCode = Utils.checkCode(mAc, json);
                if (checkCode) {
                    initJson(json);
                    leftAdapter.notifyDataSetChanged();
                    if (AllTypeList.size() > 0) {
                        AllTypeList.get(0).setCheck(true);
                        ArrayList<ShopTypeModel> jsonList = getJsonList(AllTypeList.get(0).getGoods_category_id());
                        TimeTypeAdapter adapter = new TimeTypeAdapter(getChildFragmentManager(), jsonList);
                        idViewPager.setAdapter(adapter);
                        idTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                        idTabLayout.setupWithViewPager(idViewPager);
                    }
                    if (idMultipleStatusView != null) {
                        idMultipleStatusView.showContent();
                    }
                } else {
                    if (idMultipleStatusView != null) {
                        idMultipleStatusView.showError();
                    }
                }
            }

            @Override
            public void onError(Exception e) {
                idMultipleStatusView.showError();
            }
        });

    }

    private void initJson(String typeJson) {
        try {
            JSONObject jsonObject = new JSONObject(typeJson);
            JSONObject dataJson = jsonObject.getJSONObject("data");
            listJson = dataJson.getJSONObject("list");
            JSONArray jsonArray = listJson.getJSONArray("0");
            AllTypeList.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                ShopTypeModel typeModel = new ShopTypeModel();
                JSONObject index = jsonArray.getJSONObject(i);
                typeModel.setGoods_category_id(index.getString("goods_category_id"));
                typeModel.setGoods_category_name(index.getString("goods_category_name"));
                AllTypeList.add(typeModel);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initClick() {
        idListViewLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    ArrayList<ShopTypeModel> jsonList = getJsonList(AllTypeList.get(i).getGoods_category_id());
                    TimeTypeAdapter adapter = new TimeTypeAdapter(getChildFragmentManager(), jsonList);
                    idViewPager.setAdapter(adapter);
                    idTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                    idTabLayout.setupWithViewPager(idViewPager);
                    for (int j = 0; j < AllTypeList.size(); j++) {
                        ShopTypeModel shopTypeModel = AllTypeList.get(j);
                        if (j == i){
                            shopTypeModel.setCheck(true);
                        }else{
                            shopTypeModel.setCheck(false);
                        }
                    }
                    leftAdapter.notifyDataSetChanged();
            }
        });
        idTvCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedMaps.size() > 0){
                    GuadanNextDialog dialog = new GuadanNextDialog(mAc,GuadanTimeShopTypeFragment.this);
                    dialog.show();
                }else{
                    showToast("还未选中商品");
                }
            }
        });
    }

    //再次挂单
    private void initGuadan(){
        HttpRequest.postUrl(Api.GUADAN_ORDER_NEXT)
                .addParams("SelectedGoodsStr",goodsStr)
                .addParams("gid",gid)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode){
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.GUADAN_INFO_REFRESH,true));
                            dismissProgressDialog();
                            mAc.finish();
                        }
                    }
                    @Override
                    public void onError(Exception e) {

                    }
                });

    }

    //生成商品字符串
    private void createStr() {
        for (String key : selectedMaps.keySet()) {
            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(key);
            goodsStr = goodsStr + shopSkuInfoModel.getSku_id() + "|" + shopSkuInfoModel.getBuy_num() + "|" + shopSkuInfoModel.getGoods_type() +
                    "|";
            if (StringUtils.isEmpty(shopSkuInfoModel.getEmplyeeStr())){
                goodsStr =  goodsStr +  ",";
            }else{
                goodsStr =  goodsStr + shopSkuInfoModel.getEmplyeeStr() + ",";
            }
        }
        if (goodsStr.length() > 0){
            goodsStr = goodsStr.substring(0, goodsStr.length() - 1);
        }
    }

    private ArrayList<ShopTypeModel> getJsonList(String type) {
        ArrayList<ShopTypeModel> mylist = new ArrayList<>();
        ShopTypeModel shopTypeModels = new ShopTypeModel();
        shopTypeModels.setGoods_category_id(type);
        shopTypeModels.setGoods_category_name("全部");
        mylist.add(shopTypeModels);
        JSONArray jsonArray = null;
        try {
            jsonArray = listJson.getJSONArray(type);
            for (int i = 0; i < jsonArray.length(); i++) {
                ShopTypeModel typeModel = new ShopTypeModel();
                JSONObject index = jsonArray.getJSONObject(i);
                typeModel.setGoods_category_id(index.getString("goods_category_id"));
                typeModel.setGoods_category_name(index.getString("goods_category_name"));
                mylist.add(typeModel);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mylist;
    }

    private void initAdapter() {
        leftAdapter = new CommonAdapter<ShopTypeModel>(getContext(), R.layout.item_list_left, AllTypeList) {
            @Override
            protected void convert(ViewHolder viewHolder, ShopTypeModel item, int position) {
                viewHolder.setText(R.id.id_textView, item.getGoods_category_name() + "");
                TextView idTv = viewHolder.getView(R.id.id_textView);
                RelativeLayout rlayout = viewHolder.getView(R.id.id_rlayout_all);
                if (item.isCheck()){
                    rlayout.setBackgroundColor(getResources().getColor(R.color.bg_white));
                    idTv.setTextColor(getResources().getColor(R.color.wjx_content_txt));
                }else{
                    rlayout.setBackgroundColor(getResources().getColor(R.color.wjx_type_list_bg));
                    idTv.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                }
                TextView idTvBuyNum = viewHolder.getView(R.id.id_tv_buy_num);
                int num = 0;
                for (String key:selectedMaps.keySet()) {
                    ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(key);
                    if (item.getGoods_category_id().equals(shopSkuInfoModel.getGoods_category_parent_id())) {
                        num += shopSkuInfoModel.getBuy_num();
                    }
                }
                if (num > 0){
                    idTvBuyNum.setVisibility(View.VISIBLE);
                    idTvBuyNum.setText(num+"");
                }else{
                    idTvBuyNum.setVisibility(View.GONE);
                    idTvBuyNum.setText("0");
                }
            }
        };
        idListViewLeft.setAdapter(leftAdapter);
    }

    @Override
    public void payMoney() {
        createStr();
        showProgressDialog();
        initGuadan();
    }

    class TimeTypeAdapter extends FragmentStatePagerAdapter {
        private ArrayList<ShopTypeModel> list;

        public TimeTypeAdapter(FragmentManager fm, ArrayList<ShopTypeModel> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return list.get(position).getGoods_category_name();
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = TimeShopListFragment.getInstentce(list.get(position).getGoods_category_id());

            return fragment;
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
